package com.handpay.zztong.hp.ui;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

import com.handpay.framework.ui.HPEditText;

public class HPBankCardEdit extends HPEditText
{
	
	private boolean	isRun	= false;
	private String	d		= "";
	
	public HPBankCardEdit(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		setBankCardTypeOn();
	}
	
	/**
	 * 打开银行开分割模式
	 */
	public void setBankCardTypeOn()
	{
		HPBankCardEdit.this.addTextChangedListener(new TextWatcher()
		{
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count)
			{
				if (isRun)
				{
					isRun = false;
					return;
				}
				isRun = true;
				d = "";
				String newStr = s.toString();
				newStr = newStr.replace(" ", "");
				
				int index = 0;
				while ((index + 4) < newStr.length())
				{
					d += (newStr.substring(index, index + 4) + " ");
					index += 4;
				}
				d += (newStr.substring(index, newStr.length()));
				int i = getEditTextCursorIndex(HPBankCardEdit.this);
				
				HPBankCardEdit.this.setText(d);
				try
				{
					
					if (i % 5 == 0 && before == 0)
					{
						if (i + 1 <= d.length())
						{
							HPBankCardEdit.this.setSelection(i + 1);
						}
						else
						{
							HPBankCardEdit.this.setSelection(d.length());
						}
					}
					else if (before == 1 && i < d.length())
					{
						HPBankCardEdit.this.setSelection(i);
					}
					else if (before == 0 && i < d.length())
					{
						HPBankCardEdit.this.setSelection(i);
					}
					else
						HPBankCardEdit.this.setSelection(d.length());
				}
				catch (Exception e)
				{
				}
				
			}
			
			// **获取EditText光标所在的位置*//*
			public int getEditTextCursorIndex(EditText editText)
			{
				return editText.getSelectionStart();
				
			}
			
			// **向EditText指定光标位置插入字符串*//*
			// private void insertText(EditText editText, String mText){ }
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
				
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
				
			}
		});
	}
}